import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Log } from './log.entity';
import { LogRepository } from './log.repository';

@Injectable()
export class LogService {
  constructor(
    @InjectRepository(Log)
    private logRepository: LogRepository,
  ) { }

  async findAll(query: any = {}): Promise<any[]> {
    try {
      const where: any = {};
      if (query.robotId) {
        where.robotId = query.robotId;
      }
      if (query.userId) {
        where.userId = query.userId;
      }

      // 添加分页
      const take = query.pageSize ? parseInt(query.pageSize) : 20;
      const skip = query.page ? (parseInt(query.page) - 1) * take : 0;

      const [logs, total] = await this.logRepository.findAndCount({
        where,
        take,
        skip,
        order: {
          createDate: 'DESC'
        }
      });

      // 格式化响应
      return logs.map(log => {
        const formattedLog: any = {
          ...log,
          msgContent: log.msgContent || '{}',
          msgType: log.msgType || 'text',
          remark: log.remark || '',
          content: log.msgContent, // 为了前端兼容性
        };

        // 格式化日期为字符串
        formattedLog.createDateString = log.createDate
          ? log.createDate.toISOString()
          : new Date().toISOString();

        formattedLog.updateDateString = log.updateDate
          ? log.updateDate.toISOString()
          : new Date().toISOString();

        formattedLog.createTime = log.createDate
          ? log.createDate.toISOString()
          : new Date().toISOString();

        return formattedLog;
      });
    } catch (error) {
      console.error('获取日志记录失败:', error);
      return []; // 返回空数组而不是抛出错误
    }
  }

  async create(logData: any): Promise<Log> {
    try {
      const log = new Log();
      log.robotId = logData.robotId;
      log.taskId = logData.taskId || null;
      log.userId = logData.userId;
      log.methond = logData.methond || '0'; // 默认为手动
      log.msgType = logData.msgType || 'text';
      log.msgContent = logData.msgContent;
      log.remark = logData.remark || '';
      log.status = logData.status || '1'; // 默认成功

      console.log('保存日志记录:', {
        robotId: log.robotId,
        userId: log.userId,
        msgType: log.msgType,
        methond: log.methond,
        status: log.status,
        contentLength: log.msgContent?.length || 0,
      });

      return await this.logRepository.save(log);
    } catch (error) {
      console.error('创建日志记录失败:', error.message, error.stack);
      throw new Error('创建日志记录失败: ' + error.message);
    }
  }

  async findOne(id: number): Promise<any> {
    const log = await this.logRepository.findOne({ where: { id } });

    if (log) {
      // 添加格式化的字符串日期
      const formattedLog: any = {
        ...log,
        content: log.msgContent, // 为了前端兼容性
        createDateString: log.createDate
          ? log.createDate.toISOString()
          : new Date().toISOString(),
        updateDateString: log.updateDate
          ? log.updateDate.toISOString()
          : new Date().toISOString(),
        createTime: log.createDate
          ? log.createDate.toISOString()
          : new Date().toISOString()
      };

      return formattedLog;
    }

    return log;
  }
}